package cn.mcch.investigator.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.mcch.investigator.R;
import cn.mcch.investigator.activity.ChooseCarTypeActivity;
import cn.mcch.investigator.activity.OrderExportActivity;
import cn.mcch.investigator.dialog.BaseDialog;
import cn.mcch.investigator.dialog.CancelRescueDialog;
import cn.mcch.investigator.dialog.CarCodeDialog;
import cn.mcch.investigator.dialog.ExitDialog;
import cn.mcch.investigator.dialog.LoadingDialog;
import cn.mcch.investigator.dialog.MoreRecommendListDialog;
import cn.mcch.investigator.listener.OnResponseListener;
import cn.mcch.investigator.model.bean.CarType;
import cn.mcch.investigator.model.bean.OrderExport;
import cn.mcch.investigator.model.bean.RecommendCarTypeBean;
import cn.mcch.investigator.model.impl.CreateTaskModelImpl;
import cn.mcch.investigator.observer.InvestigatorObserver;
import cn.mcch.investigator.observer.InvestigatorObserverable;
import cn.mcch.investigator.presenter.impl.CreateTaskPresenterImpl;
import cn.mcch.investigator.utils.ConstantUtil;
import cn.mcch.investigator.utils.DialogUtils;
import cn.mcch.investigator.utils.JsonUtils;
import cn.mcch.investigator.utils.ToastUtils;
import cn.mcch.investigator.viewdelegate.impl.CreateTaskViewDelegateImpl;

/**
 * Created by Administrator on 2016/12/16.
 */
public class CreateTaskFragment extends BaseFragment<CreateTaskViewDelegateImpl, CreateTaskModelImpl, CreateTaskPresenterImpl> implements InvestigatorObserver, OnResponseListener, View.OnFocusChangeListener, RadioGroup.OnCheckedChangeListener {

    private CarCodeDialog carCodeDialog;
    private BaseDialog orderDialog;
    private LoadingDialog loadingDialog;
    private CancelRescueDialog cancelRescueDialog;
    private int mode;
    private int modeOrderAttr = 1;
    private int modeRiskAreaUrban = 2;
    private int modeRiskAreaDistrict = 3;
    private int modeIntentionAreaUrban = 4;
    private int modeIntentionAreaDistrict = 5;
    private int modeOrderPrice = 6;
    private int modeOrderStyle = 7;
    private int modeRecommend = 8;

    public CreateTaskFragment() {
        super();
        isLoadData = true;
    }

    @Override
    public Class<CreateTaskPresenterImpl> getPresenterClass() {
        return CreateTaskPresenterImpl.class;
    }

    @Override
    public void createFirstView() {
        InvestigatorObserverable.addObserver(this);
        mPresenter.createFirstView(getActivity().getApplicationContext(), R.layout.layout_loading, this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        InvestigatorObserverable.deleteObserver(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void initData() {
        Map<String, String> params = new LinkedHashMap<>();
        mPresenter.initData(ConstantUtil.ACT_CONF, params, getActivity().getApplicationContext(), this, R.layout.fragment_create_task);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sb_order_Export:
                // 导入案件
                Intent intentOrderExport = new Intent(getActivity(), OrderExportActivity.class);
                startActivity(intentOrderExport);
                break;
            case R.id.sb_choose_car_code:
                // 弹出选择车牌对话框
                carCodeDialog = DialogUtils.showCarCodeDialog(getFragmentManager(), this, getResources().getStringArray(R.array.car_code), 8);
                break;
            case R.id.sb_confirm:
                // 选择完车牌
                if (TextUtils.isEmpty(carCodeDialog.getCarCode())) {
                    ToastUtils.showToast("车牌号不能为空");
                    return;
                }
                mPresenter.setCarCode(carCodeDialog.getCarCode());
                carCodeDialog.dismiss();
                carCodeDialog = null;
                break;
            case R.id.sb_choose_car_type:
                // 打开选择车型界面
                Intent intent = new Intent(getActivity(), ChooseCarTypeActivity.class);
                startActivity(intent);
                break;
            case R.id.sb_order_attr:
                // 弹出选择属性对话框
                mode = modeOrderAttr;
                orderDialog = DialogUtils.showOrderAttrListDialog(1, getFragmentManager(), this, mPresenter.confBean.order_attr);
                break;
            case R.id.sb_risk_area_urban:
                // 弹出选择出险区域对话框
                mode = modeRiskAreaUrban;
                orderDialog = DialogUtils.showRiskAreaUrbanListDialog(1, getFragmentManager(), this, mPresenter.confBean.area);
                break;
            case R.id.sb_risk_area_district:
                // 弹出选择出险区域对话框
                mode = modeRiskAreaDistrict;
                orderDialog = DialogUtils.showOrderAttrListDialog(2, getFragmentManager(), this, mPresenter.confBean.area.get(mPresenter.riskAreaUrban).child);
                break;
            case R.id.sb_intention_area_urban:
                // 弹出选择意向区域对话框
                mode = modeIntentionAreaUrban;
                orderDialog = DialogUtils.showRiskAreaUrbanListDialog(2, getFragmentManager(), this, mPresenter.confBean.area);
                break;
            case R.id.sb_intention_area_district:
                // 弹出选择意向区域对话框
                mode = modeIntentionAreaDistrict;
                orderDialog = DialogUtils.showOrderAttrListDialog(3, getFragmentManager(), this, mPresenter.confBean.area.get(mPresenter.intentionAreaUrban).child);
                break;
            case R.id.sb_order_price:
                // 弹出选择估损金额对话框
                mode = modeOrderPrice;
                orderDialog = DialogUtils.showOrderAttrListDialog(4, getFragmentManager(), this, mPresenter.confBean.order_price);
                break;
            case R.id.sb_order_style:
                // 弹出选择救援类型对话框
                mode = modeOrderStyle;
                orderDialog = DialogUtils.showOrderAttrListDialog(5, getFragmentManager(), this, mPresenter.confBean.order_style);
                break;
            case R.id.sb_yes_rescue:
                // 新增或编辑案件
                if (mPresenter.verifyInput()) {
                    loadingDialog = DialogUtils.showLoadingDialog(getFragmentManager(), String.format("正在%s案件，请稍后...", orderExport == null ? "新增" : "编辑"));
                    mPresenter.editOrder(2, this);
                }
                break;
            case R.id.sb_cancel_rescue:
                // 取消救援，弹出确认对话框
                if (orderExport == null) {
                    ToastUtils.showToast("新增案件不允许取消");
                } else {
                    cancelRescueDialog = DialogUtils.showCancelRescueDialog(getFragmentManager(), this, orderExport.sn);
                }
                break;

            case R.id.sb_yes_cancel_rescue:
                // 确定取消救援，调用接口
                loadingDialog = DialogUtils.showLoadingDialog(getFragmentManager(), "正在取消案件，请稍后...");
                mPresenter.cancelRescue(1, this, cancelRescueDialog.getOther(), cancelRescueDialog.getViewText(R.id.se_yes_cancel_rescue));
                break;
            case R.id.tv_more_recommend:
                // 显示更多推修车行对话框
                mode = modeRecommend;
                orderDialog = DialogUtils.showMoreRecommendListDialog(getFragmentManager(), this, recommendList);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        orderDialog.dismiss();
        orderDialog = null;
        boolean searchResult = false;
        // 选择属性
        if (mode == modeOrderAttr) {
            if (position != mPresenter.orderAttr) {
                // 获取推修车行信息
                searchResult = true;
            }
            mPresenter.setOrderAttr(position);
            if (searchResult) {
                mPresenter.searchRecommend(3, this);
            }
        } else if (mode == modeRiskAreaUrban) {
            // 选择出险区域
            mPresenter.setRiskAreaUrban(position);
        } else if (mode == modeRiskAreaDistrict) {
            // 选择出险区域
            mPresenter.setRiskAreaDistrict(position);
        } else if (mode == modeIntentionAreaUrban) {
            // 选择意向区域
            if (position != mPresenter.intentionAreaUrban) {
                // 获取推修车行信息
                searchResult = true;
            }
            mPresenter.setIntentionAreaUrban(position);
            if (searchResult) {
                mPresenter.searchRecommend(3, this);
            }
        } else if (mode == modeIntentionAreaDistrict) {
            // 选择意向区域
            if (position != mPresenter.intentionAreaDistrict) {
                // 获取推修车行信息
                searchResult = true;
            }
            mPresenter.setIntentionDistrict(position);
            if (searchResult) {
                mPresenter.searchRecommend(3, this);
            }
        } else if (mode == modeOrderPrice) {
            // 选择估损金额
            mPresenter.setOrderPrice(position);
        } else if (mode == modeOrderStyle) {
            // 选择救援方式
            mPresenter.setOrderStyle(position);
        } else if (mode == modeRecommend) {
            // 选择救援方式
            mPresenter.setSelectRecommend(position);
        }
    }

    private OrderExport orderExport;

    @Override
    public void notify(int type, Object data) {
        switch (type) {
            case 100:
            case 200:
            case 300:
                // 选择完车型，设置车型
                mPresenter.setCarType(((CarType) data));
                // 获取推修车行信息
                mPresenter.searchRecommend(3, this);
                break;
            case 500:
                // 获取选择的可导入的案件
                OrderExport order = (OrderExport) data;
                orderExport = order;
                mPresenter.setOrderExport(order);
                // 获取推修车行信息
                mPresenter.searchRecommend(3, this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBefore(int id) {

    }

    @Override
    public void onAfter(boolean result, int id) {
        switch (id) {
            case 1:
            case 2:
                loadingDialog.dismiss();
                // 取消案件成功，关闭取消案件对话框
                if (id == 1 && result) {
                    cancelRescueDialog.dismiss();
                }
                break;
            case 3:
                // 是否有推修车行
                mPresenter.resetRecommend(result);
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(String json, int id) {
        switch (id) {
            case 1:
                ToastUtils.showToast("取消案件成功");
                orderExport = null;
                mPresenter.reset();
                break;
            case 2:
                ToastUtils.showToast(String.format("%s案件成功", orderExport == null ? "新增" : "编辑"));
                orderExport = null;
                mPresenter.reset();
                break;
            case 3:
                // 获取推修车行成功
                recommendList = JsonUtils.fromJsonToList(json, RecommendCarTypeBean.class);
                mPresenter.setRecommend(recommendList);
                break;
            default:
                break;
        }
    }

    private List<RecommendCarTypeBean> recommendList;

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        String text = ((TextView) v).getText().toString().trim();
        if (!hasFocus && !TextUtils.isEmpty(text)) {
            // 获取推修车行信息
            mPresenter.searchRecommend(3, this);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        mPresenter.searchRecommend(3, this);

    }
}
